﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;
using WebUI.Controls;
using System.Collections;

namespace WebUI
{
    public partial class Repair : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            btnUpdatePrice.Visible = SessionUser.Admin;

            if(!IsPostBack)
            {
                Utilities.LoadDropDownList(ddlBrand, Brands.LoadAllActiveBrands().DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID);
                
                Customers cust = Customers.GetAllActiveCustomers();
                cust.Sort = Customers.ColumnNames.CustomerName + " asc";
                ddlCustomer.DataTextField = Customers.ColumnNames.CustomerName;
                ddlCustomer.DataValueField = Customers.ColumnNames.ID;
                ddlCustomer.DataSource = cust.DefaultView;
                ddlCustomer.DataBind();
                ListItem defaultCust = new ListItem("Cash Sales", "Sales");
                ddlCustomer.Items.Add(defaultCust);
                ddlCustomer.SelectedValue = defaultCust.Value;

                LoadRepairBoxes();
                Utilities.LoadDropDownList(ddlProblem, Problems.GetAllActiveProblems().DefaultView, Problems.ColumnNames.Description, Problems.ColumnNames.ID);

                bookingJobs = null;
                bookingJobProblems = null;
                SelectedProblems = null;
                btnSubmit.Enabled = SessionUser.BranchID == Branches.CurrentBranchID;
            }

            txtDealer.Visible = SessionUser.Admin;
            txtSpecial.Visible = SessionUser.Admin;
            rbDealer.Visible = SessionUser.Admin;
            rbSpecial.Visible = SessionUser.Admin;
        }


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstSelectedProblems.SelectedIndex >= 0)
            {
                ListItem item = lstSelectedProblems.Items[lstSelectedProblems.SelectedIndex];
                SelectedProblems.Filter = RepairJobProblems.ColumnNames.RepairModelProblemID + "=" + item.Value;
                SelectedProblems.MarkAsDeleted();
                SelectedProblems.Filter = "";
                lstSelectedProblems.Items.RemoveAt(lstSelectedProblems.SelectedIndex);

                UpdateJobAmount();
                updateSelectedProblems.Update();
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            lstSelectedProblems.Items.Clear();
            SelectedProblems = null;
            UpdateJobAmount();
            updateSelectedProblems.Update();
            btnSubmit.Enabled = SessionUser.BranchID == Branches.CurrentBranchID;
        }

        protected void ddlProblem_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlProblem.SelectedIndex > 0 && ddlModel.SelectedIndex > 0)
            {
                RepairModelProblems p = RepairModelProblems.GetProblem(int.Parse(ddlModel.SelectedValue), int.Parse(ddlProblem.SelectedValue));
                if (p.RowCount > 0)
                {
                    txtRPP.Text = p.s_RPP;

                    if (SessionUser.Admin)
                    {
                        txtDealer.Text = p.s_StandardPrice;
                        txtSpecial.Text = p.s_SpecialPrice;
                    }
                }
                else
                {
                    txtRPP.Text = "0";
                    txtDealer.Text = "0";
                    txtSpecial.Text = "0";
                }

                rbCustomer.Checked = true;

                updatePrice.Update();
            }
            else
            {
                txtRPP.Text = "0";
                txtDealer.Text = "0";
                txtSpecial.Text = "0";
                updatePrice.Update();
            }
        }

        protected void ddlCustomer_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            int custID = 0;

            try
            {
                custID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {

            }

            View_Customers cust = View_Customers.GetCustomerByID(custID);

            if (cust.RowCount > 0)
            {
                txtCustomerPhone.Text = cust.s_Phone;
                rbDealer.Checked = cust.Price == CustomerType.CustomerPrice.DealerPrice;
                rbCustomer.Checked = cust.Price == CustomerType.CustomerPrice.SalePrice;
                rbSpecial.Checked = cust.Price == CustomerType.CustomerPrice.PartnerPrice;

                if (!SessionUser.Admin)
                {
                    rbCustomer.Checked = true;
                    rbDealer.Checked = false;
                    rbSpecial.Checked = false;
                }

                LoadRepairBoxes();
                RepairJob job = RepairJob.GetCurrentRepairBoxByCustID(custID);
                if (job.RowCount > 0)
                    ddlRepairBox.SelectedValue = job.s_RepairBoxID;
                updateRepairBox.Update();
            }
            else
            {
                txtCustomerPhone.Text = "";
                rbCustomer.Checked = true;
                rbDealer.Checked = false;
                rbSpecial.Checked = false;
            }

            updatePrice.Update();
            RefreshCustPrice();

            ClearJob();
            updateRequestList.Update();
        }

        const string WHOLESALE = "WHOLESALE";
        const string SALE = "RETAIL";
        const string PARTNER = "PARTNER";

        private void RefreshCustPrice()
        {
            int custID;
            try
            {
                custID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                custID = -1;
            }

            View_Customers cust = View_Customers.GetCustomerByID(custID);
            if (cust.Price == CustomerType.CustomerPrice.SalePrice)
            {
                lblCustPrice.Text = SALE;
            }
            else if (cust.Price == CustomerType.CustomerPrice.DealerPrice)
                lblCustPrice.Text = WHOLESALE;
            else if (cust.Price == CustomerType.CustomerPrice.PartnerPrice)
                lblCustPrice.Text = PARTNER;
        }

        protected void ddlCustomer_OnItemInserted(object sender, EventArgs e)
        {
            lblCustPrice.Text = SALE;
        }

        public String SelectedProblemsKey
        {
            get 
            {
                if (ViewState["SelectedProblemsKey"] == null)
                    ViewState["SelectedProblemsKey"] = "SelectedProblemsKey";
                return ViewState["SelectedProblemsKey"].ToString();
            }
        }

        const string JOB_AMOUNT = "JobAmount";
        public decimal JobAmount
        {
            get
            {
                return (decimal)ViewState[JOB_AMOUNT];
            }
            set
            {
                ViewState[JOB_AMOUNT] = value;
            }
        }

        public RepairJobProblems SelectedProblems
        {
            get
            {
                return Session[SelectedProblemsKey] as RepairJobProblems;
            }
            set
            {
                Session[SelectedProblemsKey] = value;
            }
        }

        void UpdateJobAmount()
        {
            if (SelectedProblems == null)
            {
                lblTotal.Text = String.Format("{0:C}", 0);
                return;
            }

            Decimal s = 0;
            SelectedProblems.Rewind();
            for (int i = 0; i < SelectedProblems.RowCount; i++)
            {
                s += SelectedProblems.Price;
                SelectedProblems.MoveNext();
            }

            lblTotal.Text = String.Format("{0:C}", s);
            JobAmount = s;
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            lstSelectedProblems.Items.Clear();
            SelectedProblems.Rewind();
            for (int i = 0; i < SelectedProblems.RowCount; i++)
            {
                String problemDesc = SelectedProblems.s_Description;
                String problemCost = String.Format("{0:C}", SelectedProblems.Price);
                ListItem item = new ListItem(problemDesc + " - " + problemCost, SelectedProblems.RepairModelProblemID.ToString());
                lstSelectedProblems.Items.Add(item);

                SelectedProblems.MoveNext();
            }

            UpdateJobAmount();
        }

        protected void btnAddProblem_OnClick(Object sender, EventArgs e)
        {
            if (ddlProblem.SelectedIndex > 0 && ddlModel.SelectedIndex > 0)
            {
                RepairModelProblems p = RepairModelProblems.GetProblem(int.Parse(ddlModel.SelectedValue), int.Parse(ddlProblem.SelectedValue));
                if (SelectedProblems == null)
                    SelectedProblems = new RepairJobProblems();

                SelectedProblems.Filter = RepairJobProblems.ColumnNames.RepairModelProblemID + "=" + p.ID.ToString();
                if (SelectedProblems.RowCount > 0)
                {
                    SelectedProblems.Filter = "";
                    ShowErrorMessage(panelError, "(*) Problem has been already added!");
                    updateError.Update();
                    return;
                }

                SelectedProblems.AddNew();
                SelectedProblems.RepairModelProblemID = p.ID;
                SelectedProblems.Description = ddlProblem.SelectedItem.Text;
                SelectedProblems.BranchID = Branches.CurrentBranchID;
                if (rbCustomer.Checked)
                    SelectedProblems.s_Price = txtRPP.Text;
                else if (rbDealer.Checked)
                    SelectedProblems.s_Price = txtDealer.Text;
                else if (rbSpecial.Checked)
                    SelectedProblems.s_Price = txtSpecial.Text;

                String problemDesc = SelectedProblems.s_Description;
                String problemCost = String.Format("{0:C}", SelectedProblems.Price);
                ListItem item = new ListItem(problemDesc + " - "  + problemCost, p.s_ID);
                lstSelectedProblems.Items.Add(item);
                SelectedProblems.Filter = "";
                UpdateJobAmount();
                updateSelectedProblems.Update();
            }
        }

        protected void ddlBrand_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBrand.SelectedIndex > 0)
            {
                if(ddlProblem.Items.Count > 0)
                    ddlProblem.SelectedIndex = 0;
                Utilities.LoadDropDownList(ddlModel, RepairModels.GetModelsByBrandID(int.Parse(ddlBrand.SelectedValue)).DefaultView, RepairModels.ColumnNames.ModelName, RepairModels.ColumnNames.ID);
            }
        }

        public int DumpID
        {
            get { return ViewState["DumpID"] != null ? (int)ViewState["DumpID"] : 0; }
            set { ViewState["DumpID"] = value; }
        }

        protected void btnAddJob_OnClick(object sender, EventArgs e)
        {
            try
            {
                if (SelectedProblems == null)
                {
                    ShowErrorMessage(panelError, "(*) No problem to repair!");
                    updateError.Update();
                    return;
                }

                SelectedProblems.Filter = "";
                if (SelectedProblems.RowCount <= 0)
                {
                    ShowErrorMessage(panelError, "(*) No problem to repair!");
                    updateError.Update();
                    return;
                }

                Sequence seq = new Sequence();

                RepairJob job = GetBookingJobs();
                job.AddNew();
                job.ID = --DumpID;
                job.Deleted = false;
                job.CreatedByUser = SessionUser.ID;
                job.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                job.LastModifiedByUser = SessionUser.ID;
                job.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                //job.CustomerPhone = txtCustomerPhone.Text;
                job.s_RepairModelID = ddlModel.SelectedValue;
                job.BrandName = ddlBrand.SelectedItem.Text;
                job.ModelName = ddlModel.SelectedItem.Text;
                job.RepairNo = seq.GetNewID("Repair");
                job.s_IMEI = txtIMEI.Text;
                job.StatusID = RepairStatus.NoStatus;
                job.IsRetail = rbCustomer.Checked;
                //job.CustomerName = ddlCustomer.SelectedItem.Text;
                //job.RepairBoxID = int.Parse(ddlRepairBox.SelectedValue);
                job.BranchID = Branches.CurrentBranchID;
                if (hidIMEI.Value != "")
                    job.IsRedo = true;

                //int custID = 0;
                //try { custID = int.Parse(ddlCustomer.SelectedValue); }
                //catch (Exception ex1) { }

                //if (custID > 0)
                //    job.CustomerID = custID;
                String accessory = "";
                for (int i = 0; i < panelAccessory.Controls.Count; i++)
                {
                    if (panelAccessory.Controls[i] is CheckBox)
                    {
                        if (i < panelAccessory.Controls.Count - 1)
                            accessory += ((CheckBox)panelAccessory.Controls[i]).Checked ? ((CheckBox)panelAccessory.Controls[i]).Text + "," : "";
                        else
                            accessory += ((CheckBox)panelAccessory.Controls[i]).Checked ? ((CheckBox)panelAccessory.Controls[i]).Text : "";
                    }
                }
                if (accessory.EndsWith(","))
                    accessory = accessory.Remove(accessory.Length - 1);
                job.s_Accessories = accessory;

                RepairJobProblems jobProblems = GetBookingJobProblems();
                SelectedProblems.Rewind();
                for (int i = 0; i < SelectedProblems.RowCount; i++)
                {
                    SelectedProblems.RepairJobID = job.ID;

                    jobProblems.AddNew();
                    jobProblems.s_Description = SelectedProblems.s_Description;
                    jobProblems.s_ID = SelectedProblems.s_ID;
                    jobProblems.s_PreviousPrice = SelectedProblems.s_PreviousPrice;
                    jobProblems.s_Price = SelectedProblems.s_Price;
                    jobProblems.s_RepairJobID = SelectedProblems.s_RepairJobID;
                    jobProblems.s_RepairModelProblemID = SelectedProblems.s_RepairModelProblemID;
                    jobProblems.BranchID = Branches.CurrentBranchID;
                    SelectedProblems.MoveNext();
                }

                gridRequests.SourceObject = job;
                gridRequests.JobProblems = jobProblems;
                gridRequests.Refresh();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Repair.aspx.cs", "btnAddJob_OnClick", ex.StackTrace);
                ShowErrorMessage(panelError, "(*) " + ex.Message);
                updateError.Update();
            }
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            Hashtable jobMap = new Hashtable();
            try
            {
                tx.BeginTransaction();
                
                int custID = 0;
                try { custID = int.Parse(ddlCustomer.SelectedValue); }
                catch (Exception ex1) 
                {
                    Customers cust = new Customers();
                    cust.AddNew();
                    cust.CustomerType = CustomerType.DefaultType;
                    cust.BranchID = Branches.CurrentBranchID;
                    cust.Deleted = false;
                    cust.TotalAmount = 0;
                    cust.PaidAmount = 0;
                    cust.Password = Utilities.CreateMD5Hash(Utilities.GetConfigAppSetting("DefaultPassword"));
                    cust.LastModifiedByUser = SessionUser.ID;
                    cust.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    cust.Mobile = txtCustomerPhone.Text;
                    cust.Phone = txtCustomerPhone.Text;
                    cust.s_CustomerName = ddlCustomer.SelectedItem.Text;
                    cust.Save();
                    custID = cust.ID;
                    ddlCustomer.SelectedItem.Value = custID.ToString();
                }

                RepairJob job = GetBookingJobs();
                job.Rewind();
                for (int i = 0; i < job.RowCount; i++)
                {
                    job.CustomerPhone = txtCustomerPhone.Text;
                    if (custID > 0)
                        job.CustomerID = custID;
                    job.CustomerName = ddlCustomer.SelectedItem.Text;
                    jobMap[job.ID] = job.RepairNo;
                    job.BranchID = Branches.CurrentBranchID;
                    job.RepairBoxID = int.Parse(ddlRepairBox.SelectedValue);
                    job.MoveNext();
                }

                if (!string.IsNullOrEmpty(txtLoanIMEI.Text.Trim()))
                {
                    LoanPhones lp = LoanPhones.GetLoanPhoneByIMEI(txtLoanIMEI.Text.Trim());
                    if (lp.RowCount > 0 && lp.Deleted == false && lp.Free)
                    {
                        lp.Free = false;
                        job.LoanPhoneID = lp.ID;
                        job.LoanPhoneReturn = false;
                        lp.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        lp.Save();
                    }
                }

                job.Save();

                job.Rewind();
                for (int i = 0; i < job.RowCount; i++)
                {
                    View_RepairJobs.UpdateRepairBoxStatus(job.RepairBoxID);
                    job.MoveNext();
                }

                RepairJobProblems jobProblems = GetBookingJobProblems();
                jobProblems.Rewind();
                for (int i = 0; i < jobProblems.RowCount; i++)
                {
                    string repairNo = (string)jobMap[jobProblems.RepairJobID];
                    job.Filter = RepairJob.ColumnNames.RepairNo + " = '" + repairNo + "'";
                    jobProblems.RepairJobID = job.ID;
                    jobProblems.BranchID = Branches.CurrentBranchID;
                    jobProblems.MoveNext();
                }
                jobProblems.Save();
                
                jobMap.Clear();

                tx.CommitTransaction();
                job.Filter = "";
                btnPrint.Visible = true;
                btnSubmit.Visible = false;
                ShowHintMessage(panelError, "(*) New Repair Jobs has been submitted!");
                updateError.Update();
                if(chkPrint.Checked)
                    PrintRequest();
            }
            catch(Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("Repair.aspx.cs", "btnSubmit_OnClick", ex.StackTrace);
                ShowErrorMessage(panelError, "(*) There's an error in submitting jobs. Please contact your administrator: " + ex.Message);
                updateError.Update();
            }
        }

        protected void btnNew_OnClick(object sender, EventArgs e)
        {
            lstSelectedProblems.Items.Clear();
            SelectedProblems = null;
            ClearJob();
            JobAmount = 0;
            UpdateJobAmount();
            txtIMEI.Text = "";
            btnPrint.Visible = false;
            btnSubmit.Visible = true;
            hidIMEI.Value = "";
            LoadRepairBoxes();
        }

        private void ClearJob()
        {
            bookingJobs = new RepairJob(); ;
            bookingJobProblems = new RepairJobProblems(); ;
            gridRequests.SourceObject = bookingJobs;
            gridRequests.JobProblems = bookingJobProblems;
            txtLoanIMEI.Text = "";
            txtLoanPhone.Text = "";
            gridRequests.Refresh();
        }

        protected void btnDeleteJob_Click(object sender, EventArgs e)
        {
            gridRequests.DeleteCheckedItems();
            gridRequests.Refresh();
        }

        protected void btnClearJob_Click(object sender, EventArgs e)
        {
            ClearJob();
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintRequest();
        }

        const string BOOKING_JOB = "BOOKING_JOB";
        RepairJob bookingJobs
        {
            get { return (RepairJob)Session[BOOKING_JOB]; }
            set { Session.Remove(BOOKING_JOB); Session[BOOKING_JOB] = value; }
        }

        const string BOOKING_JOB_PROBLEMS = "BOOKING_JOB_PROBLEMS";
        RepairJobProblems bookingJobProblems
        {
            get { return (RepairJobProblems)Session[BOOKING_JOB_PROBLEMS]; }
            set { Session.Remove(BOOKING_JOB_PROBLEMS); Session[BOOKING_JOB_PROBLEMS] = value; }
        }

        RepairJob GetBookingJobs()
        {
            if (bookingJobs == null)
                bookingJobs = new RepairJob();
            return bookingJobs;
        }

        RepairJobProblems GetBookingJobProblems()
        {
            if (bookingJobProblems == null)
                bookingJobProblems = new RepairJobProblems();
            return bookingJobProblems;
        }

        protected void btnRedo_OnClick(object sender, EventArgs e)
        {
            if (hidIMEI.Value == "")
                return;
            try
            {
                int id = int.Parse(hidIMEI.Value);
                RepairJob job = new RepairJob();
                job.LoadByPrimaryKey(id);
                if (job.RowCount > 0)
                {
                    RepairModels model = new RepairModels();
                    model.LoadByPrimaryKey(job.RepairModelID);

                    RepairJobProblems prob = RepairJobProblems.GetProblemsByRepairID(job.ID);
                    
                    if (model.RowCount > 0)
                    {
                        if (job.s_CustomerID == "")
                        {
                            ListItem newCust = new ListItem(job.s_CustomerName, job.s_CustomerName);
                            ddlCustomer.Items.Add(newCust);
                            ddlCustomer.SelectedValue = newCust.Value;
                        }
                        else
                            ddlCustomer.SelectedValue = job.s_CustomerID;

                        ddlBrand.SelectedValue = model.s_BrandID;
                        Utilities.LoadDropDownList(ddlModel, RepairModels.GetModelsByBrandID(int.Parse(ddlBrand.SelectedValue)).DefaultView, RepairModels.ColumnNames.ModelName, RepairModels.ColumnNames.ID);
                        ddlModel.SelectedValue = model.s_ID;
                        txtIMEI.Text = job.s_IMEI;
                        txtCustomerPhone.Text = job.s_CustomerPhone;

                        SelectedProblems = new RepairJobProblems();
                        lstSelectedProblems.Items.Clear();
                        for (int i = 0; i < prob.RowCount; i++)
                        {
                            SelectedProblems.AddNew();
                            SelectedProblems.s_Description = "Redo: " + prob.s_Description;
                            SelectedProblems.s_Price = "0";
                            SelectedProblems.s_RepairJobID = job.s_ID;
                            SelectedProblems.s_RepairModelProblemID = prob.s_RepairModelProblemID;
                            SelectedProblems.BranchID = Branches.CurrentBranchID;
                            String problemDesc = "Redo: " + prob.s_Description;
                            String problemCost = String.Format("{0:C}", 0);
                            ListItem item = new ListItem(problemDesc + " " + problemCost, prob.s_ID);
                            lstSelectedProblems.Items.Add(item);

                            prob.MoveNext();
                            
                        }

                        UpdateJobAmount();
                        updateJob.Update();
                    }
                }
            }
            catch(Exception ex)
            {
                ErrorLog.WriteToFile("Repair.aspx.cs", "btnRedo_OnClick", ex.StackTrace);
                ShowErrorMessage(panelError, "(*) " + ex.Message);
                updateError.Update();

            }
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return this.ResolveClientUrl("~/EditPages/PrintHandler.aspx?key=") + PrintKey;
        }

        private void PrintRequest()
        {
            try
            {
                RepairRequestCtrl ivcViewer = (RepairRequestCtrl)LoadControl(@"~/Controls/POSControls/RepairRequestCtrl.ascx");
                Session[PrintKey] = ivcViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Repair.aspx.cs", "PrintRequest", ex.StackTrace);
            }
        }

        void LoadRepairBoxes()
        {
            string selected = ddlRepairBox.SelectedValue;
            Utilities.LoadDropDownListNoSort(ddlRepairBox, View_RepairBoxes.GetAllActiveBoxes().DefaultView, View_RepairBoxes.ColumnNames.Status,
                View_RepairBoxes.ColumnNames.ID, "--Select--");
            ddlRepairBox.SelectedValue = selected;
        }

        protected void btnRefreshRepairBox_Click(object sender, EventArgs e)
        {
            LoadRepairBoxes();
        }

        protected void txtLoanIMEI_OnTextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtLoanIMEI.Text.Trim()))
            {
                LoanPhones p = LoanPhones.GetLoanPhoneByIMEI(txtLoanIMEI.Text);
                if (p.RowCount > 0)
                {
                    if ((!p.IsColumnNull(LoanPhones.ColumnNames.Free) && !p.Free) || p.Deleted)
                    {
                        txtLoanIMEI.Text = "";
                        txtLoanPhone.Text = "This phone is not available.";
                        txtLoanPhone.CssClass = "labelError";
                        return;
                    }

                    txtLoanPhone.Text = p.ProductName;
                    txtLoanPhone.CssClass = "labelMessage";
                }
                else
                {
                    txtLoanIMEI.Text = "";
                    txtLoanPhone.Text = "No existing loan phone has this IMEI number.";
                    txtLoanPhone.CssClass = "labelError";
                }
            }
        }

        protected void btnUpdatePrice_OnClick(object sender, EventArgs e)
        {
            try
            {
                if (ddlProblem.SelectedIndex > 0 && ddlModel.SelectedIndex > 0)
                {
                    RepairModelProblems p = RepairModelProblems.GetProblem(int.Parse(ddlModel.SelectedValue), int.Parse(ddlProblem.SelectedValue));

                    if (txtRPP.Text != "")
                        p.s_RPP = txtRPP.Text;

                    if (txtDealer.Text != "")
                        p.s_StandardPrice = txtDealer.Text;

                    if (txtSpecial.Text != "")
                        p.s_SpecialPrice = txtSpecial.Text;

                    p.Save();

                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "alert('Price updated!');", true);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("", "", ex.Message + ex.StackTrace);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "alert('Cannot update price!');", true);
            }
        }
    }
}